<template>
  <div class="login-page">
    <van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field
      v-model="formObj.username"
      name="username"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="formObj.password"
      type="password"
      name="password"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button  round block type="primary" native-type="submit">
      提交
    </van-button>
  </div>
</van-form>

  </div>
</template>

<script lang="ts" setup>
import { showToast ,showConfirmDialog} from 'vant'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const router = useRouter()
const formObj = reactive({
  username:'',
  password:'',
})
onMounted(() => {
  // 清除token
  userStore.setToken('')
})
onActivated(() => {
  console.log('路由激活')
})

const onSubmit = async () => {
  // 定义响应数据的类型
interface LoginRes {
  token: string;
  code:number
  // 其他可能的响应字段
}
  const res = await UserService.login(formObj)
  if(res.code ==200){
    // 将token存到状态管理
    userStore.setToken(res.token)
    // 请求用户信息
    const res2 = await UserService.getUserInfo()
    if(res2.code==200){
      userStore.setUserInfo(res2.data)
      // 跳转首页
      router.push({
        name:'home'
      })
    }
  }
}
const openSure = ()=>{
  showConfirmDialog({
  title: '标题',
  message:
    '如果解决方法是丑陋的，那就肯定还有更好的解决方法，只是还没有发现而已。',
})
  .then(() => {
    // on confirm
  })
  .catch(() => {
    // on cancel
  });
}
</script>

<style lang="scss">

</style>
